#!coding=utf-8
import os,sys,getopt


def spilt(filename, singlefilesize=1, filerange=":", outdir=''):
    """
        @rtype: object
        @param filename: file to be splited
        @param singlefilesize: single file size,MB
        @param outdir:
        @param filerange:
    """
    singlefilesize = singlefilesize*1024*1024
    #获取文件名
    basenmae = os.path.basename(filename)
    #获取文件绝对路径，带文件名
    filefullname = os.path.abspath(filename)
    basedir = os.path.split(filefullname)[0]
    fileSize = os.path.getsize(filename)
    singlefilenums = fileSize/(singlefilesize)
    if fileSize%(singlefilesize) != 0:
        singlefilenums += 1
    print "max file index:",singlefilenums
    if outdir == "" :
        outdir = basedir+"/"+basenmae.split(".")[0]+"/"
        if not os.path.exists(outdir):
            os.mkdir(outdir)
    if outdir[-1] != '/':
        outdir += '/'

    _filerange = filerange.replace(' ','').split(":")
    filerangestart = _filerange[0]

    filerangeend = _filerange[1]
    if filerangestart == '':
        filerangestart = 0
    else:
        if filerangestart.startswith('-'):
            filerangestart = filerangestart[1]
            filerangestart = singlefilenums - int(filerangestart)
        else:
            filerangestart = int(filerangestart)
    if filerangeend == '':
        filerangeend = singlefilenums
    else:
        if filerangeend.startswith('-'):
            filerangeend = filerangeend[1]
            filerangeend = singlefilenums - int(filerangeend)
        else:
            filerangeend = int(filerangeend)

    with open(filename,'rb') as fd:
        for i in xrange(singlefilenums):
            print "The file number %d is on the processing" % i
            if i in range(filerangestart, filerangeend):
                newfilename = "%s%d_%s"%(outdir,i,basenmae)
                if os.path.exists(newfilename):
                    print "The file %s is exist, delete it." % newfilename
                    os.remove(newfilename)
                with open(newfilename, 'wb') as new_fd:
                    new_fd.write(fd.read(singlefilesize))
            else:
                fd.seek(singlefilesize,1)


def sort_opts(opts):
    '''
    将opts中的选项按照默认选项顺序排序
    默认选线顺序为：
    default=['-b','-t','-s','--cmd','-d','-c','-f']
    '''
    #命令默认执行顺序
    default=['-f','-o','-r','-s','-h']
    options=[]
    #对命令进行默认排序
    [[options.append(elem) for elem in opts if elem[0] == defopt] for defopt in default]
    return options

def usage():
    print '-f               -- file to be spilted'
    print '-o               -- output directory,default:current directory'
    print '-r               -- file index range, :deault: ":"'
    print '-s               -- single file size, default: 50'
    print '-h               -- show this help'


if __name__ == "__main__":
    filename = ""
    ourdir=""
    filerange=":"
    singlefilesize=50

    if len(sys.argv) > 1:
        opts, args = getopt.getopt(sys.argv[1:], "f:o:r:s:h")
        sorted_opts = sort_opts(opts)
        if sorted_opts != []:
            for op, value in sorted_opts:
                if op == '-f':
                    try:
                        if not os.path.exists(value):
                            print 'file not exist'
                            sys.exit(1)
                        filename = value
                    except:
                        sys.exit(1)
                elif op == '-o':
                    ourdir = value
                elif op == '-r':
                    filerange = value
                elif op == '-s':
                    singlefilesize = int(value)
                elif op == '-h':
                    usage()
    else:
        usage()
        sys.exit(0)

    spilt(filename, singlefilesize, filerange, ourdir)
